package cn.itsource.user.controller;

import cn.itsource.annotation.PreAuthorize;
import cn.itsource.user.domain.User;
import cn.itsource.user.query.UserQuery;
import cn.itsource.user.service.IUserService;
import cn.itsource.util.JsonResult;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * 接口类：用户User
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户接口类")
public class UserController {
    @Autowired
    private IUserService userService;

    /**
     * 查询所有
     * @return
     */
    @ApiOperation(value = "查询所有")
    @GetMapping
    public List<User> findAll(){
        return userService.findAll();
    }

    /**
     * 查询单个
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public User findOne(@PathVariable("id")Long id){
        return userService.findOne(id);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id")Long id){
        try {
            userService.delete(id);
            return JsonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    /**
     * 添加或修改
     * @param user
     * @return
     */
    @PutMapping
    public JsonResult addOrUpdate(@RequestBody User user){
        try {
           if(user.getId()==null){
               userService.add(user);
           }else{
               userService.update(user);
           }
            return JsonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    @PreAuthorize(name = "用户批量删除",sn = "user:patchDelete",descs = "用户批量删除")
    public JsonResult patchDel(@RequestBody Long[] ids){
        try {
            userService.patchDel(ids);
            return JsonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    /**
     * 分页查询+高级查询
     * @param userQuery
     * @return
     */
    @PostMapping
    public PageInfo<User> queryPage(@RequestBody UserQuery userQuery){
        return userService.queryPage(userQuery);
    }
}
